package com.mune.gulimall.ware.service.mq;

import com.mune.common.to.mq.StockLockedTo;
import com.mune.common.to.order.OrderTo;
import com.mune.gulimall.ware.service.WareSkuService;
import com.rabbitmq.client.Channel;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;

@Component
@RabbitListener(queues = "stock.release.stock.queue")
public class MQListener {

  @Autowired
  WareSkuService wareSkuService;

  @RabbitHandler
  public void handleStockLockedRelease(StockLockedTo to, Message message, Channel channel) throws IOException {
    System.out.println("收到解锁库存的消息");
    boolean locked = wareSkuService.handleOrderStockRelease(to);
    if (locked) {
      channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
    } else {
      channel.basicReject(message.getMessageProperties().getDeliveryTag(), true);
    }
  }

  @RabbitHandler
  public void handleOrderCloseRelease(OrderTo orderTo, Message message, Channel channel) throws IOException {
    try {
      wareSkuService.handleOrderCloseRelease(orderTo);
      // 手动删除消息
      channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
    } catch (Exception e) {
      // 解锁失败 将消息重新放回队列，让别人消费
      channel.basicReject(message.getMessageProperties().getDeliveryTag(), true);
    }
  }
}
